﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Data.SqlClient;
using System.Windows.Forms;
using Capstone_project.DatabaseAccessLayer;

namespace Capstone_project.DatabaseAccessLayer
{
    class ConnectData
    {
        private DataTable dtable;
        public DataTable DTable { get; set; }
        private SqlDataAdapter adap;
        public SqlDataAdapter DAdapter { get; set; }
        private SqlConnection con = Common.con;
        
        public DataTable getData(string sql, bool setDataProperties = false)
        {
            if (setDataProperties)
            {
                adap = new SqlDataAdapter(sql, con);
                dtable = new DataTable();
                adap.Fill(dtable);
                return dtable;
            }
            else
            {
                SqlDataAdapter dataAdapter = new SqlDataAdapter(sql, con);
                DataTable dataTable = new DataTable();
                dataAdapter.Fill(dataTable);
                return dataTable;
            }
        }
        public DataTable saveAll()
        {
            int numrecord = 0;
            SqlTransaction tran = null;
            try
            {
                if (con.State == ConnectionState.Closed)
                    con.Open();
                tran = con.BeginTransaction();
                adap.SelectCommand.Transaction = tran;
                SqlCommandBuilder combui = new SqlCommandBuilder(adap);
                numrecord = adap.Update(dtable);
                tran.Commit();
            }
            catch (Exception ex)
            {
                if (tran != null)
                    tran.Rollback();
                MessageBox.Show("Loi " + ex.Message);
            }
            if (con.State == ConnectionState.Open)
                con.Close();
            return dtable; ;
        }
        public string getLastID(string tblname, string fieldname)
        {
            string sql = "SELECT TOP 1 " + fieldname + " FROM " + tblname + " ORDER BY " + fieldname + " DESC";
            DataTable dt = this.getData(sql);
            return dt.Rows[0][fieldname].ToString();
        }
    }
}
